/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.org.pslava.codingtest;

import ua.org.pslava.codingtest.factory.ProductFactory;
import ua.org.pslava.codingtest.model.Basket;
import ua.org.pslava.codingtest.model.BasketItem;
import ua.org.pslava.codingtest.model.Product;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Encapsulates a functionality of sale terminal. <br/>
 *
 * 
 * @author Vyacheslav Panasyuk.
 */
public class PointOfSaleTerminal implements IPointOfSale {

    private final String ORDER_ERROR = "Order is not set!";
    private final String UNKNOWN_PRODUCT = "PRODUCT IS UNKNOWN";
    private Basket basket;
    private String order;
    private ProductFactory productFabric;

    public PointOfSaleTerminal() {
        productFabric = new ProductFactory();
        basket = new Basket();
    }

    public Double calculateTotal() {
        Double result = -1.0;
        try {
            parseOrder();
            result = basket.calculate();
        } catch (Exception ex) {
            Logger.getLogger(PointOfSaleTerminal.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public void AddOrder(String order) {
        this.order = order;
    }

    public void setProductFabric(ProductFactory productFabric) {
        this.productFabric = productFabric;
    }

    private void parseOrder() throws Exception {
        if (order == null || order.equals("")) {
            throw new Exception(ORDER_ERROR);
        }
        StringTokenizer st = new StringTokenizer(order.toUpperCase(), order, true);
        while (st.hasMoreTokens()) {
            String prodName = st.nextToken();
            Product product = productFabric.getProduct(prodName);
            if (product != null) {
                basket.add(new BasketItem(product));
            } else {
                throw new Exception(UNKNOWN_PRODUCT);
            }
        }

    }
}
